//
//  JLNewsDetailController.m
//  LIangeNews
//
//  Created by sun on 16/1/17.
//  Copyright © 2016年 sun. All rights reserved.
//

#import "JLNewsDetailController.h"
#import "JLHeadline.h"
#import "JLHttpManager.h"
#import "JLNewsDetail.h"
#import "MBProgressHUD+HMExtension.h"
#import "JLNewsDetailimg.h"
@interface JLNewsDetailController ()<UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property(strong,nonatomic)JLNewsDetail * newsDetail;
@property(strong,nonatomic)NSURLSessionDataTask * session;

@end

@implementation JLNewsDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"暴走漫画";
    [self setupRequestAndData];
    self.webView.scrollView.bounces = NO;
    self.webView.scrollView.showsVerticalScrollIndicator = NO;
    self.webView.scrollView.showsHorizontalScrollIndicator = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.webView.delegate = self;
    self.webView.scrollView.bounces = NO;
}
-(void)setupRequestAndData{
    NSString * strUrl =[NSString stringWithFormat:@"http://c.m.163.com/nc/article/%@/full.html",self.headline.docid];
 self.session = [[JLHttpManager shareManager] requestWithJLMethod:GET urlString:strUrl parameters:nil finished:^(NSDictionary * responseObject, NSError *error) {
       if (error) {
           [MBProgressHUD showError:@"网络信号不佳,请稍后再试"];
           NSLog(@"----%@",error);
       }else{
           [responseObject writeToFile:@"/Users/liang/Desktop/11.plist" atomically:YES];
           self.newsDetail = [JLNewsDetail newsDetailWithDict:responseObject[self.headline.docid]];
           
           [self showDetailNews];
       }
   }];
}
-(void)dealloc{
    [self.session cancel];
    
}
-(void)showDetailNews{
    NSMutableString * html = [NSMutableString stringWithCapacity:100];
    [html appendString:@"<html>"];
    [html appendString:@"<head>"];
    [html appendFormat:@"<link rel =\"stylesheet\" href=\"%@\">",[[NSBundle mainBundle] URLForResource:@"JLDetail.css" withExtension:nil]];
    [html appendString:@"</head>"];
    [html appendString:@"<body>"];
    [html appendString:[self setupBody]];
    [html appendString:@"</body>"];
    [html appendString:@"</html>"];
    [self.webView loadHTMLString:html baseURL:nil];
    
}
-(NSString *)setupBody{
    NSMutableString * body = [NSMutableString stringWithCapacity:20];
    [body appendFormat:@"<div class = \"title\">%@</div>",self.newsDetail.title];
    [body appendFormat:@"<div class = \"ptime\">%@</div>",self.newsDetail.ptime];
    [body appendString:self.newsDetail.body];
    for (JLNewsDetailimg * img in self.newsDetail.img) {
        NSMutableString * imgHtml =[NSMutableString stringWithCapacity:20];
        [imgHtml appendString:@"<div class=\"img-parent\">"];
      NSArray * arrayWH = [img.pixel componentsSeparatedByString:@"*"];
        CGFloat width = [arrayWH.firstObject floatValue];
        CGFloat height = [arrayWH.lastObject floatValue];
        CGFloat maxWidth = [UIScreen mainScreen].bounds.size.width * 0.9;
        if (width > maxWidth ) {
            height =   height * maxWidth / width ;
            width = maxWidth;
        }
        NSString * onload =@"this.onclick = function(){"
        " window.location.href = 'jl:saveImageToAblum:&' + this.src};";
        [imgHtml appendFormat:@"<img onload=\"%@\" width=\"%f\" height=\"%f\" src=\"%@\"><div>",onload,width,height,img.src];
        [imgHtml appendString:@"</div>"];
        [body replaceOccurrencesOfString:img.ref withString:imgHtml options:NSCaseInsensitiveSearch range:NSMakeRange(0, body.length)];
     }
   return  body;
}
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString * urlStr = request.URL.absoluteString;
    NSRange  rang =  [urlStr rangeOfString:@"jl"];
    if (rang.length > 0) {
        NSString * medthodAndParam = [urlStr substringFromIndex:NSMaxRange(rang)+1];
       NSArray * array = [medthodAndParam componentsSeparatedByString:@"&"];
        NSString * medthodStr = array.firstObject;
        NSString * param = nil;
        if (array.count > 1) {
            param = array.lastObject;
        }
        SEL medthodSEL = NSSelectorFromString(medthodStr);
        if ([self respondsToSelector:medthodSEL] ) {
#pragma clang diagnostic push
            // 让 clang 忽略 -Warc-performSelector-leaks 警告信息
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            [self performSelector:medthodSEL withObject:param];
#pragma clang diagnostic pop
        }
        return NO;
    }
    return YES;
}
-(void)saveImageToAblum:(NSString *)imgSrc{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"是否要将选中的图片保存到图片相册" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:imgSrc]];
        NSData * data = [[NSURLCache sharedURLCache] cachedResponseForRequest:request].data;
        UIImage * img = [UIImage imageWithData:data];
        UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"亚麻得" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {
        [MBProgressHUD showError:@"保存失败"];
    }else{
        [MBProgressHUD showSuccess:@"保存成功"];
    }
}
@end
